#pragma once

#include <pthread.h>
#include <string>
#include <functional>
#include <cassert>
namespace Thread_CBR
{
    using func_t = std::function<void *(void *)>;
    const int num = 1024;
    class Thread
    {
    private:
        static void *start_routine(void *args)
        {
            Thread *_this = static_cast<Thread *>(args);
            return _this->callback();
        }

    public:
        Thread(func_t func, void *args = nullptr) : _func(func), _args(args)
        {
            char namebuffer[num];
            snprintf(namebuffer, sizeof(namebuffer), "thread-%d", threadnum++);
            _name = namebuffer;
        }
        void start()
        {
            int n = pthread_create(&_tid, nullptr, start_routine, this);
            assert(n == 0);
            (void)n;
        }
        void join()
        {
            int n = pthread_join(_tid, nullptr);
            assert(n == 0);
            (void)n;
        }
        std::string threadname()
        {
            return _name;
        }
        void *callback()
        {
            return _func(_args);
        }
        ~Thread() {}

    private:
        std::string _name;
        void *_args;
        func_t _func;
        pthread_t _tid;
        static int threadnum;
    };
    int Thread::threadnum = 1;
}